package com.strongbj.iot.devices.amazonreader.response.entity;

import java.util.ArrayList;
import java.util.List;

import com.strongbj.core.util.ByteUtil;
/**
 * 标签解析
 * @author yuzhantao
 *
 */
public class LabelEntityFactory implements IEntityFactory<List<BaseLabelEntity>> {
	@Override
	public List<BaseLabelEntity> parse(byte[] datas){
		List<BaseLabelEntity> result = new ArrayList<>();
		if(datas==null || datas.length==0) return result;
		int offset=0;
		try{
			while(offset<datas.length){
				byte  type = datas[offset++];
				BaseLabelEntity lab=null;
				switch(type){
				case 0x06:	// led标签
					lab = this.parseLedLabel(datas,offset);
					break;
				}
				if(lab!=null){
					offset+=lab.getLength();
					result.add(lab);
				}
			}
		}catch(Exception e){}
		return result;
	}
	
	private LedLabelEntity parseLedLabel(byte[] datas,int offset){
		LedLabelEntity lab = new LedLabelEntity();
		lab.setType((byte)6);
		// 设置标签id，id以ip地址格式形式体现
		StringBuilder sbId=new StringBuilder();
		sbId.append(ByteUtil.byteToInt(datas[offset++])+".");
		sbId.append(ByteUtil.byteToInt(datas[offset++])+".");
		sbId.append(ByteUtil.byteToInt(datas[offset++])+".");
		sbId.append(ByteUtil.byteToInt(datas[offset++]));
		lab.setId(sbId.toString());
		
		byte dataField = datas[offset++];
		// 设置电量电压
		switch((dataField >> 6) & 0x3){
			case 1:
				lab.setVoltage(LedLabelVoltageState.Normal);
				break;
			case 2:
				lab.setVoltage(LedLabelVoltageState.Alarm);
				break;
		}
		// 获取按键状态
		switch((dataField >> 4) & 0x3){
		case 1:
			lab.setKeyState(LedLabelKeyState.KeyDown);
			break;
		case 2:
			lab.setKeyState(LedLabelKeyState.KeyUp);
			break;
		}
		// 设置红色LED
		lab.setRedLed(((dataField >> 3) & 0x1)==1?LedLabelLightState.On:LedLabelLightState.Off);
		// 设置绿色LED
		lab.setGreenLed(((dataField >> 3) & 0x1)==1?LedLabelLightState.On:LedLabelLightState.Off);
		// 设置蓝色LED
		lab.setBlueLed(((dataField >> 3) & 0x1)==1?LedLabelLightState.On:LedLabelLightState.Off);
		// 设置白色LED
		lab.setWhiteLed(((dataField >> 3) & 0x1)==1?LedLabelLightState.On:LedLabelLightState.Off);
		
		byte[] baseStationShortAddress = new byte[8];
		System.arraycopy(datas, offset, baseStationShortAddress, 0, baseStationShortAddress.length);
		lab.setBaseStationShortAddress(baseStationShortAddress);
		return lab;
	}
}
